import {get, post, put} from './http.js';

$(document).ready(function () {
    // 初始化数据
    initData();
});

// 获取后端地址列表
function initData() {
    // 初始化地址列表
    initAddressList();
    // 初始化地址选择器
    initAddressSelector();
    // 初始化地址弹框事件
    initAddressModal();
    // 初始化支付方式
    initPaymentMethods();
    // 初始化商品信息
    initGoodsInfo();

    // 立即支付按钮点击事件
    $('.submit-btn').click(function () {
        submitOrder();
    });
}

// 初始化地址弹框事件
function initAddressModal() {
    // 打开弹框
    $(document).on('click', '.add-address', function () {
        $('#addressModal').fadeIn();
    });

    // 关闭弹框
    $('.close-btn, .btn-cancel').click(function () {
        $('#addressModal').fadeOut();
        resetForm();
    });

    // 点击弹框外部关闭
    $('#addressModal').click(function (e) {
        if (e.target === this) {
            $(this).fadeOut();
            resetForm();
        }
    });

    // 保存地址
    $('.btn-save').click(function () {
        if (validateForm()) {
            saveAddress();
        }
    });

    // 编辑按钮点击事件
    $(document).on('click', '.btn-edit', function (e) {
        e.stopPropagation(); // 阻止事件冒泡
        const addressId = $(this).data('id');
        openEditModal(addressId);
    });
}

// 重置表单
function resetForm() {
    $('.address-form')[0].reset();
    $('.error-msg, .area-select-errors').remove();
    $('input, textarea, select').removeClass('error');

    // 重置省市区选择器
    $('select[name="city"]').empty().append('<option value="">请选择城市</option>');
    $('select[name="district"]').empty().append('<option value="">请选择区县</option>');

    // 清除编辑状态
    $('.btn-save').removeData('edit-id');
}

// 表单验证
function validateForm() {
    let isValid = true;
    $('.error-msg, .area-select-errors').remove();
    $('input, textarea, select').removeClass('error');

    // 验证收货人
    const name = $('input[name="name"]').val().trim();
    if (!name) {
        showError('input[name="name"]', '请输入收货人姓名');
        isValid = false;
    }

    // 验证手机号
    const phone = $('input[name="phone"]').val().trim();
    if (!/^1[3-9]\d{9}$/.test(phone)) {
        showError('input[name="phone"]', '请输入正确的手机号码');
        isValid = false;
    }

    // 验证地区选择
    const areaErrors = [];
    if (!$('select[name="province"]').val()) {
        $('select[name="province"]').addClass('error');
        areaErrors.push('请选择省份');
    }
    if (!$('select[name="city"]').val()) {
        $('select[name="city"]').addClass('error');
        areaErrors.push('请选择城市');
    }
    if (!$('select[name="district"]').val()) {
        $('select[name="district"]').addClass('error');
        areaErrors.push('请选择区县');
    }

    // 如果地区选择有错误，显示错误信息
    if (areaErrors.length > 0) {
        $('.area-select').after(`<div class="area-select-errors">${areaErrors[0]}</div>`);
        isValid = false;
    }

    // 验证详细地址
    const address = $('textarea[name="address"]').val().trim();
    if (!address) {
        showError('textarea[name="address"]', '请输入详细地址');
        isValid = false;
    }

    return isValid;
}

// 显示错误信息
function showError(selector, message) {
    $(selector).addClass('error')
        .parent().append(`<div class="error-msg">${message}</div>`);
}

// 保存地址
async function saveAddress() {
    const editId = $('.btn-save').data('edit-id');
    const addressData = {
        id: editId,
        receiverName: $('input[name="name"]').val().trim(),
        phone: $('input[name="phone"]').val().trim(),
        province: $('select[name="province"]').val(),
        city: $('select[name="city"]').val(),
        district: $('select[name="district"]').val(),
        addressDetail: $('textarea[name="address"]').val().trim(),
        postalCode: $('input[name="postalCode"]').val().trim(),
        isDefault: $('#isDefault').prop('checked') ? 1 : 0
    };

    if (editId) {
        // 编辑现有地址
        const index = savedAddresses.findIndex(addr => addr.id === editId);
        if (index !== -1) {
            savedAddresses[index] = addressData;

            // 如果编辑的是当前选中的地址，或者设置为默认地址，更新显示
            if ($(`.address-item[data-id="${editId}"]`).hasClass('active') || addressData.isDefault) {
                updateSelectedAddress(addressData);
            }
        }

        try {
            await put(`/api/address/update`, addressData);
            Notify.success('编辑地址成功');
        } catch (error) {
            Notify.error(error.response.msg);
        }
    } else {
        // 添加新地址
        try {
            await post(`/api/address/add`, addressData);
            Notify.success('添加地址成功');
        } catch (error) {
            Notify.error(error.response.msg);
        }
    }

    // 重新渲染地址列表
    await initAddressList();

    // 关闭弹框并重置
    $('#addressModal').fadeOut();
    resetForm();
    // 清除编辑状态
    $('.btn-save').removeData('edit-id');
}

// 初始化地址列表
async function initAddressList() {
    try {
        const data = await get('/api/address/list');
        savedAddresses.length = 0;
        savedAddresses.push(...data);
    } catch (error) {
        Notify.error(error.response.msg);
    }
    const $addressList = $('.address-list');
    $addressList.empty();

    // 找到默认地址或第一个地址
    const defaultAddress = savedAddresses.find(addr => addr.isDefault) || savedAddresses[0];

    // 渲染已保存的地址
    savedAddresses.forEach(address => {
        const isActive = defaultAddress && address.id === defaultAddress.id;
        const addressHtml = `
            <div class="address-item ${isActive ? 'active' : ''}" data-id="${address.id}">
                <div class="address-info" data-id="${address.id}">
                    <div class="name-phone">
                        <span class="name">${address.name}</span>
                        <span class="phone">${formatPhone(address.phone)}</span>
                    </div>
                    <div class="address-detail">
                        ${address.province}${address.city}${address.district}${address.address}
                    </div>
                    ${address.isDefault ? '<div class="default-tag">默认地址</div>' : ''}
                </div>
                <div class="address-actions">
                    <button class="btn-edit" data-id="${address.id}">编辑</button>
                </div>
            </div>
        `;
        $addressList.append(addressHtml);
    });

    // 添加"新增地址"按钮
    $addressList.append(`
        <div class="address-item add-address">
            <i class="add-icon">+</i>
            添加新地址
        </div>
    `);

    // 添加地址选择事件
    $('.address-info').click(function (e) {
        e.stopPropagation();
        const addressId = $(this).data('id');
        const selectedAddress = savedAddresses.find(addr => addr.id === addressId);
        if (selectedAddress) {
            updateSelectedAddress(selectedAddress);
        }
    });

    // 初始化默认地址信息
    initDefaultAddress();
}

// 更新选中的地址信息
function updateSelectedAddress(address) {
    if (!address) return;

    // 更新页面底部的确认信息
    $('#selectedAddress').text(`${address.province}${address.city}${address.district}${address.address}`);
    $('#selectedName').text(address.name);
    $('#selectedPhone').text(formatPhone(address.phone));

    // 更新地址列表的选中状态
    $('.address-item').removeClass('active');
    $(`.address-item[data-id="${address.id}"]`).addClass('active');
}

// 初始化地址选择器
function initAddressSelector() {
    const $province = $('select[name="province"]');
    const $city = $('select[name="city"]');
    const $district = $('select[name="district"]');

    // 清空并添加省份选项
    $province.empty().append('<option value="">请选择省份</option>');
    regionData.provinces.forEach(province => {
        $province.append(`<option value="${province.name}">${province.name}</option>`);
    });

    // 省份改变时更新城市
    $province.change(function () {
        const selectedProvince = regionData.provinces.find(p => p.name === $(this).val());
        updateCityOptions(selectedProvince);
    });

    // 城市改变时更新区县
    $city.change(function () {
        const selectedProvince = regionData.provinces.find(p => p.name === $province.val());
        const selectedCity = selectedProvince?.cities.find(c => c.name === $(this).val());
        updateDistrictOptions(selectedCity);
    });
}

// 更新城市选项
function updateCityOptions(province) {
    const $city = $('select[name="city"]');
    const $district = $('select[name="district"]');

    $city.empty().append('<option value="">请选择城市</option>');
    $district.empty().append('<option value="">请选择区县</option>');

    if (province) {
        province.cities.forEach(city => {
            $city.append(`<option value="${city.name}">${city.name}</option>`);
        });
    }
}

// 更新区县选项
function updateDistrictOptions(city) {
    const $district = $('select[name="district"]');

    $district.empty().append('<option value="">请选择区县</option>');

    if (city) {
        city.districts.forEach(district => {
            $district.append(`<option value="${district.name}">${district.name}</option>`);
        });
    }
}

// 格式化手机号码
const formatPhone = (phone) => {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}

// 打开编辑弹框
function openEditModal(addressId) {
    $('.modal-header>h3').text('编辑收货地址');
    // 查找对应的地址数据
    const address = savedAddresses.find(addr => addr.id === addressId);
    if (!address) return;

    // 填充表单数据
    $('input[name="name"]').val(address.name);
    $('input[name="phone"]').val(address.phone);
    $('input[name="postalCode"]').val(address.postalCode);
    $('textarea[name="address"]').val(address.address);
    $('#isDefault').prop('checked', address.isDefault);

    // 设置省市区
    $('select[name="province"]').val(address.province);
    // 触发省份选择事件，更新城市列表
    $('select[name="province"]').trigger('change');

    setTimeout(() => {
        $('select[name="city"]').val(address.city);
        // 触发城市选择事件，更新区县列表
        $('select[name="city"]').trigger('change');

        setTimeout(() => {
            $('select[name="district"]').val(address.district);
        }, 100);
    }, 100);

    // 修改保存按钮的行为
    $('.btn-save').data('edit-id', addressId);

    // 显示弹框
    $('#addressModal').fadeIn();
}

// 初始化支付方式
function initPaymentMethods() {
    // 支付方式切换
    $('.payment-item').click(function () {
        // 移除其他支付方式的选中状态
        $('.payment-item').removeClass('active');
        // 添加当前支付方式的选中状态
        $(this).addClass('active');

        // 更新选中的支付方式
        const paymentMethod = $(this).data('method');
        updateSelectedPayment(paymentMethod);
    });
}

// 更新选中的支付方式
function updateSelectedPayment(method) {
    // 这里可以添加更新支付方式的相关逻辑
    console.log('选中的支付方式：', method);
}

// 初始化商品信息
function initGoodsInfo() {
    // 从 URL 获取商品信息
    const urlParams = new URLSearchParams(window.location.search);


    let from = urlParams.get('from');
    if (from && from === 'cart') {
        // 购物车项ID
        const itemId = urlParams.get('itemId');
        let itemIdArr = itemId.split(',');
        post('/api/cart/get-product-info', itemIdArr).then(productInfo => {
            // {
            //     "id": "1932651433114341380",
            //     "title": "restfulToolkitX 暗紫色 256G",
            //     "spec": "[{\"attrId\":1932651432921403394,\"attrName\":\"颜色\",\"valueId\":1932651432921403396,\"valueName\":\"暗紫色\"},{\"attrId\":1932651432921403395,\"attrName\":\"容量\",\"valueId\":1932651432921403112,\"valueName\":\"256G\"}]",
            //     "price": 0.02,
            //     "image": "images/product1.png",
            //     "count": 96
            // }

            // 遍历data 生成goodsHtml
            let goodsHtml = '';
            var totalPrice = 0;
            productInfo.forEach(item => {
                goodsHtml += `
                <div class="goods-item">
                    <div class="goods-img">
                        <img src="${item.image}" alt="${item.title}">
                    </div>
                    <div class="goods-info">
                        <div class="goods-title">${item.title}</div>
                        <div class="goods-spec">${item.spec}</div>
                    </div>
                    <div class="goods-price">
                        <div class="price">¥${item.price.toFixed(2)}</div>
                        <div class="count" data-id=${item.id}>x${item.count}</div>
                    </div>
                </div>
            `;

                // 总金额
                totalPrice += item.price * item.count
            })
            $('.goods-list').html(goodsHtml);
            // 更新总价和应付金额
            // const totalPrice = productInfo.price * count;
            $('#totalPrice').text(`¥${totalPrice.toFixed(2)}`);
            $('#finalPrice').text(`¥${totalPrice.toFixed(2)}`);
            $('#confirmPrice').text(`¥${totalPrice.toFixed(2)}`);
        });
    } else if (from && from === 'productDetail') {
        const skuId = urlParams.get('skuId');
        const count = parseInt(urlParams.get('count')) || 1;
        // 模拟商品数据（实际项目中应该从后端获取）
        const productInfo = {
            id: skuId,
            title: "Apple iPhone 15 Pro Max",
            spec: "暗紫色 256GB",
            price: 9999.00,
            image: "images/product1-1.png"
        };

        get('/api/sku/' + skuId).then(data => {
                productInfo.title = data.skuName;
                productInfo.spec = data.skuDesc;
                productInfo.price = data.skuPrice;
                productInfo.image = data.skuPicUrl;

                // 渲染商品信息
                const goodsHtml = `
                <div class="goods-item">
                    <div class="goods-img">
                        <img src="${productInfo.image}" alt="${productInfo.title}">
                    </div>
                    <div class="goods-info">
                        <div class="goods-title">${productInfo.title}</div>
                        <div class="goods-spec">${productInfo.spec}</div>
                    </div>
                    <div class="goods-price">
                        <div class="price">¥${productInfo.price.toFixed(2)}</div>
                        <div class="count">x${count}</div>
                    </div>
                </div>
            `;

                $('.goods-list').html(goodsHtml);

                // 更新总价和应付金额
                const totalPrice = productInfo.price * count;
                $('#totalPrice').text(`¥${totalPrice.toFixed(2)}`);
                $('#finalPrice').text(`¥${totalPrice.toFixed(2)}`);
                $('#confirmPrice').text(`¥${totalPrice.toFixed(2)}`);
            }
        ).catch(error => {
            Notify.error(error.response.msg);
        });
    } else {
        alert("参数错误!!!");
    }
}

// 初始化默认地址信息
function initDefaultAddress() {
    // 查找默认地址
    const defaultAddress = savedAddresses.find(addr => addr.isDefault);
    // 如果有默认地址，显示默认地址信息
    if (defaultAddress) {
        updateSelectedAddress(defaultAddress);
    }
    // 如果没有默认地址，显示第一个地址
    else if (savedAddresses.length > 0) {
        updateSelectedAddress(savedAddresses[0]);
    }
}

// 立即支付（生成待支付单）
function submitOrder() {
    // 获取选中的地址
    const selectedAddressId = $('.address-item.active').data('id');
    const selectedAddress = savedAddresses.find(addr => addr.id === selectedAddressId);

    if (!selectedAddress) {
        alert('请选择收货地址');
        return;
    }

    // 获取选中的支付方式
    const paymentMethod = $('.payment-item.active').data('method');
    if (!paymentMethod) {
        alert('请选择支付方式');
        return;
    }

    // 订单金额
    const amount = $('#confirmPrice').text().replace('¥', '');
    // 入参
    var orderCreateReq = {};

    const urlParams = new URLSearchParams(window.location.search);
    let from = urlParams.get('from');
    if (from && from === 'cart') {
        // const urlParams = new URLSearchParams(window.location.search);
        // const skuId = urlParams.get('skuId');
        // const count = parseInt(urlParams.get('count')) || 1;

        // 获取所有<div class="count" data-id=${item.id}>x${item.count}</div>
        var orderItems = [];
        let map = $('.goods-list .goods-item .goods-price .count').map(function (index, data) {
            var productQuantity = $(this).text();
            productQuantity = productQuantity.substring(1);
            var productSkuId = $(this).attr('data-id');
            var orderItem = {productSkuId, productQuantity};
            orderItems.push(orderItem);
        });

        orderCreateReq = {
            "receiverName": selectedAddress.receiverName,
            "receiverPhone": selectedAddress.phone,
            "receiverProvince": selectedAddress.province,
            "receiverCity": selectedAddress.city,
            "receiverDistrict": selectedAddress.district,
            "receiverDetailAddress": selectedAddress.addressDetail,
            "buyerMessage": "买家留言",
            "buyerRemark": "买家备注",
            "shippingMethod": 0,
            "sourceType": 0,
            "orderItems": orderItems,
            "paymentMethod": paymentMethod,
            "couponId": 1
        }
    } else if (from && from === 'productDetail') {
        const urlParams = new URLSearchParams(window.location.search);
        const skuId = urlParams.get('skuId');
        const count = parseInt(urlParams.get('count')) || 1;

        orderCreateReq = {
            "receiverName": selectedAddress.receiverName,
            "receiverPhone": selectedAddress.phone,
            "receiverProvince": selectedAddress.province,
            "receiverCity": selectedAddress.city,
            "receiverDistrict": selectedAddress.district,
            "receiverDetailAddress": selectedAddress.addressDetail,
            "buyerMessage": "买家留言",
            "buyerRemark": "买家备注",
            "shippingMethod": 0,
            "sourceType": 0,
            "orderItems": [{
                "productSkuId": skuId,
                "productQuantity": count
            }],
            "paymentMethod": paymentMethod,
            "couponId": 1
        }
    } else {
        alert("参数错误!!!");
    }


    // 生成预付单
    post('/api/order/create', orderCreateReq).then(data => {
        Notify.success('订单创建成功');
        const {orderNo, codeUrl} = data;
        // 跳转到支付页面
        window.location.href = `payment.html?orderId=${orderNo}&amount=${amount}&paymentMethod=${paymentMethod}&codeUrl=${codeUrl}`;
    }).catch(error => {
        Notify.error(error.response.msg);
    });
}

// 生成订单号（示例）
function generateOrderId() {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const random = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
    return `${year}${month}${day}${random}`;
} 